﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using NCalc;
using SolidWorks.Interop.sldworks;
using SwParaPlatform2.dlgUIConfig;
using SwParaPlatform2.logger;

namespace SwParaPlatform2
{
    public partial class TaskPaneHost : UserControl
    {
        public Dictionary<string, Dictionary<string, Dictionary<string, string>>> parsedRules;
        public Dictionary<string, List<string>> ParaRuleMap;
        public bool bBanCb;
        private Timer tooltipTimer;
        private readonly ISwParaInterface _commonInterface;
        private dlgSubPage.dlgRename currentControl;
        //public event Action ShowMainForm;
        private ISldWorks iSwApp;

        public TaskPaneHost()
        {
            InitializeComponent();
            InitToolTipTimer();
            _commonInterface = new SwParaInterface();
            UIGrid.CurrentCellDirtyStateChanged += UIGrid_CurrentCellDirtyStateChanged;
            UIGrid.CellContentClick += DataGridView_CellContentClick;
            bBanCb = true;
            parsedRules = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
            ParaRuleMap = new Dictionary<string, List<string>>();


#if DEBUG
    oTestBtn.Visible=true;
#else
    oTestBtn.Visible=false;            
#endif
            //UIGrid.Columns["KeyCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIGrid.Columns["MaxCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIGrid.Columns["MinCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIGrid.Columns["KeyCol"].Width = 80; // 设置固定宽度
            UIGrid.Columns["MaxCol"].Width = 60; 
            UIGrid.Columns["MinCol"].Width = 60; 
        }

        private class LinkInfo
        {
            public string Action { get; set; }
            public string Path { get; set; }

            public LinkInfo(string name, string path)
            {
                Action = name;
                Path = path;
            }
        }

        private Dictionary<string, LinkInfo> linkMap = new Dictionary<string, LinkInfo>();

        private class LinkRange
        {
            public int StartIndex;
            public int Length;
            public LinkInfo Info;
        }

        private List<LinkRange> linkRanges = new List<LinkRange>();

        public void SetSwApp(ISldWorks swapp)
        {
            iSwApp = swapp;
        }

        public void InitDataView()
        {
            try
            {
                AnalyzeRules();
                GenerateMapping();
                RefreshDataGridView();
            }
            catch (Exception ex)
            {
                Logger.Instance.Log($"Error in InitDataView: {ex.Message}");
                Logger.Instance.Log($"Stack Trace: {ex.StackTrace}");
                MessageBox.Show("初始化数据视图时发生错误，请查看日志获取详细信息。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public void SetEditPartShow(bool bShow)
        {
            oDriveBtn.Visible = bShow;
            UIGrid.Visible = bShow;
        }

        public void ClearDriveView()
        {
            parsedRules = new Dictionary<string, Dictionary<string, Dictionary<string, string>>>();
            ParaRuleMap = new Dictionary<string, List<string>>();
            UIGrid.Rows.Clear();
        }


        public void RefreshDataGridView()
        {
            try
            {
                var parameterDictionary = UIConfigModel.Instance.GetGridDataDict();
                if (parameterDictionary == null)
                {
                    Logger.Instance.Log("Warning: parameterDictionary is null in RefreshDataGridView");
                    return;
                }

                UIGrid.Rows.Clear();
                bBanCb = true;

                // 按照"序号"字段对字典进行排序
                var sortedParameters = parameterDictionary
                    .OrderBy(kv => 
                    {
                        if (kv.Value.ContainsKey("序号"))
                        {
                            return Convert.ToInt32(kv.Value["序号"]);
                        }
                        return int.MaxValue; // 如果没有"序号"键，则将其放在最后
                    })
                    .ToList();

                foreach (var parameter in sortedParameters)
                {
                    InsertRowToDataGridView(UIGrid.Rows.Count, parameter.Key, triggerCallback: false, true);
                }

                bBanCb = false;

                // 手动触发 UIGrid_CurrentCellDirtyStateChanged
                foreach (DataGridViewRow row in UIGrid.Rows)
                {
                    try
                    {
                        // 设置当前行的单元格为脏状态，以便触发事件
                        UIGrid.CurrentCell = row.Cells["ValueCol"];
                        UIGrid.NotifyCurrentCellDirty(true); // 设置当前单元格为脏状态

                        // 手动调用事件处理程序
                        UIGrid_CurrentCellDirtyStateChanged(UIGrid, EventArgs.Empty);
                    }
                    catch (Exception ex)
                    {
                        Logger.Instance.Log($"Error processing row in RefreshDataGridView: {ex.Message}");
                        continue; // 继续处理下一行
                    }
                }
                UIGrid.NotifyCurrentCellDirty(false); // 设置当前单元格为脏状态
            }
            catch (Exception ex)
            {
                Logger.Instance.Log($"Error in RefreshDataGridView: {ex.Message}");
                Logger.Instance.Log($"Stack Trace: {ex.StackTrace}");
                MessageBox.Show("刷新数据视图时发生错误，请查看日志获取详细信息。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        public void HideCurrentControl()
        {
            if (currentControl != null)
            {
                this.Controls.Remove(currentControl);
                currentControl.Dispose();
                currentControl.OpenWindowBtnClick -= OnOpenWindowBtnClick;
                currentControl.SaveFileBtnClick -= OnSaveFileBtnClick;
                currentControl.ShowMainForm -= ShowMainForm1;
                currentControl = null;
            }
                
        }

        private void ToggleControl(TableLayoutPanel button, dlgSubPage.dlgRename controlToShow)
        {
            if (button.Parent is TabPage parentTabPage)
            {
                if (currentControl != null)
                {
                    HideCurrentControl();
                }

                if (currentControl == controlToShow)
                {
                    HideCurrentControl();
                    return;
                }

                currentControl = controlToShow;
                currentControl.Dock = DockStyle.Top; // 确保UserControl的宽度随着TabPage的宽度变化
                currentControl.OpenWindowBtnClick += OnOpenWindowBtnClick;
                currentControl.SaveFileBtnClick += OnSaveFileBtnClick;
                currentControl.ShowMainForm += ShowMainForm1;

                // 添加到TabPage中
                parentTabPage.Controls.Add(currentControl);

                // 获取button在TabPage中的索引
                int iIndex = parentTabPage.Controls.GetChildIndex(button);
                Logger.Instance.Log($"index        {iIndex}");

                // 设置controlToShow在button之下
                parentTabPage.Controls.SetChildIndex(currentControl, iIndex);
            }
            else
            {
                Logger.Instance.Log("Error: The button is not inside a TabPage.");
            }
        }

        public void OnSelectElement(List<string> lSearchList)
        {
            if(currentControl != null)
            {
                currentControl.OnSelectElement(lSearchList);
            }
        }

        public void RefreshTreeView()
        {
            if (currentControl != null)
            {
                currentControl.RefreshTreeView();
            }
        }
        
        public void SavaConfig(bool Pack = true)
        {
            if (currentControl != null)
            {
                currentControl.SavaConfig(Pack);
            }
        }
        
        public void ClearCurrentControlData()
        {
            if (currentControl != null)
            {
                currentControl.ClearData();
            }
        }

        public void OnCatchFail(string sTips)
        {
            if (currentControl != null)
            {
                currentControl.OnCatchFail(sTips);
            }
        }

        public void InsertRowToDataGridView(int rowIndex, string parameterKey, bool triggerCallback = true, bool checkShowRule = false)
        {
            var parameterDictionary = UIConfigModel.Instance.GetGridDataDict();

            // 检查 DataGridView 中是否已经存在该 parameterKey
            foreach (DataGridViewRow row in UIGrid.Rows)
            {
                if (row.Cells["KeyCol"].Value?.ToString() == parameterKey)
                {
                    Logger.Instance.Log($"Key '{parameterKey}' already exists in the DataGridView.");
                    return;
                }
            }

            if (!parameterDictionary.ContainsKey(parameterKey))
            {
                Logger.Instance.Log($"Key '{parameterKey}' does not exist in the dictionary.");
                return;
            }

            var parameterSettings = parameterDictionary[parameterKey];

            // 检查“显示规则”是否存在且不为空
            if (parameterSettings.ContainsKey("显示规则") && !string.IsNullOrEmpty(parameterSettings["显示规则"].ToString()) && checkShowRule)
            {
                // 如果有显示规则且不为空，则跳过这行的生成
                return;
            }

            // 插入新行
            UIGrid.Rows.Insert(rowIndex);
            UIGrid.Rows[rowIndex].Cells["KeyCol"].Value = parameterKey;

            string sDefault = parameterSettings.ContainsKey("默认值")
                                    ? parameterSettings["默认值"].ToString()
                                    : "";

            if (parameterSettings.ContainsKey("输入类型") && parameterSettings["输入类型"].ToString() != "自由填写")
            {
                var comboBoxCell = new DataGridViewComboBoxCell();

                if (parameterSettings.ContainsKey("输入列表") && parameterSettings["输入列表"] is List<string> options)
                {
                    comboBoxCell.DataSource = options;
                    // 设置默认值
                    comboBoxCell.Value = parameterSettings.ContainsKey("默认值") && options.Contains(parameterSettings["默认值"].ToString())
                                         ? parameterSettings["默认值"].ToString()
                                         : options.FirstOrDefault();
                }

                UIGrid.Rows[rowIndex].Cells["ValueCol"] = comboBoxCell;
            }
            else
            {
                var textBoxCell = new DataGridViewTextBoxCell();

                // 设置默认值
                textBoxCell.Value = parameterSettings.ContainsKey("默认值")
                                    ? parameterSettings["默认值"].ToString()
                                    : sDefault;

                UIGrid.Rows[rowIndex].Cells["ValueCol"] = textBoxCell;
                
            }

            var maxBoxCell = new DataGridViewTextBoxCell();
            var minBoxCell = new DataGridViewTextBoxCell();
            var unitBoxCell = new DataGridViewTextBoxCell();

            maxBoxCell.Value = parameterSettings.ContainsKey("最大值")
                                    ? parameterSettings["最大值"].ToString()
                                    : "";

            minBoxCell.Value = parameterSettings.ContainsKey("最小值")
                                    ? parameterSettings["最小值"].ToString()
                                    : "";
            unitBoxCell.Value = parameterSettings.ContainsKey("单位")
                                    ? parameterSettings["单位"].ToString()
                                    : "";

            UIGrid.Rows[rowIndex].Cells["MaxCol"] = maxBoxCell;
            UIGrid.Rows[rowIndex].Cells["MinCol"] = minBoxCell;
            UIGrid.Rows[rowIndex].Cells["UnitCol"] = unitBoxCell;

            var PicCell = new DataGridViewButtonCell();
            PicCell.Value = "点击查看";
            PicCell.Tag = parameterSettings["示例图"];
            UIGrid.Rows[rowIndex].Cells["PicCol"] = PicCell;

            // 注册事件处理程序


            //手动触发回调（初始化时不触发）
            if (triggerCallback)
            {
                UIGrid.CurrentCell = UIGrid.Rows[rowIndex].Cells["ValueCol"];
                UIGrid.NotifyCurrentCellDirty(true); // 设置当前单元格为脏状态
                UIGrid_CurrentCellDirtyStateChanged(UIGrid, EventArgs.Empty);
                UIGrid.NotifyCurrentCellDirty(false); // 设置当前单元格为脏状态
            }
        }


        private void UIGrid_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            Logger.Instance.Log($"UIGrid_CurrentCellDirtyStateChanged {bBanCb}: KeyCol = {UIGrid.IsCurrentCellDirty}");

            if (!bBanCb)
            {
                if (UIGrid.IsCurrentCellDirty)
                {
                    // 获取当前单元格所在的行号
                    int rowIndex = UIGrid.CurrentCell.RowIndex;
                    int colIndex = UIGrid.CurrentCell.ColumnIndex;
                    string valueColValue_Old = UIGrid.Rows[rowIndex].Cells["ValueCol"].Value?.ToString();

                    // 提交当前单元格的更改
                    UIGrid.CommitEdit(DataGridViewDataErrorContexts.Commit);

                    string valueColValue = UIGrid.Rows[rowIndex].Cells["ValueCol"].Value?.ToString();
                    string maxColValue = UIGrid.Rows[rowIndex].Cells["MaxCol"].Value?.ToString();
                    string minColValue = UIGrid.Rows[rowIndex].Cells["MinCol"].Value?.ToString();

                    var cell = UIGrid.Rows[rowIndex].Cells[colIndex];
                    if (!_commonInterface.IsInRange(valueColValue, maxColValue, minColValue))
                    {
                        Logger.Instance.Log($"输入的值不在预设范围内");
                        UIGrid.Rows[rowIndex].Cells["ValueCol"].Value = valueColValue_Old;
                        ShowToolTip(rowIndex, colIndex, "输入的值不在预设范围内");
                        return;
                    }
                    else
                    {
                        cell.ToolTipText = string.Empty;  // 清除 ToolTip
                    }

                    // 获取当前单元格所在行的 "KeyCol" 列的内容
                    string keyColValue = UIGrid.Rows[rowIndex].Cells["KeyCol"].Value?.ToString();

                    Logger.Instance.Log($"Row {rowIndex}: KeyCol = {keyColValue}");
                    // 在这里添加其他复杂逻辑

                    if (keyColValue != null)
                    {
                        if (ParaRuleMap.ContainsKey(keyColValue))
                        {
                            var ParaRuleList = ParaRuleMap[keyColValue];
                            var parameterDictionary = UIConfigModel.Instance.GetGridDataDict();
                            var sortedParaRuleList = ResortParaRuleList(ParaRuleList, parameterDictionary);
                            foreach (var sSubRuleKey in sortedParaRuleList)
                            {
                                if (IsRuleMatch(sSubRuleKey))
                                {
                                    InsertRowToDataGridView(rowIndex + 1, sSubRuleKey);
                                }
                                else
                                {
                                    foreach (DataGridViewRow row in UIGrid.Rows)
                                    {
                                        // 检查 "KeyCol" 列中的值是否为指定的内容
                                        if (row.Cells["KeyCol"].Value?.ToString() == sSubRuleKey)
                                        {
                                            // 移除这一行
                                            UIGrid.Rows.Remove(row);
                                            // 找到并移除后，可以直接退出循环（假设 KeyCol 中值唯一）
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        private List<string> ResortParaRuleList(List<string> ParaRuleList, Dictionary<string, Dictionary<string, object>> parameterDictionary)
        {
            return ParaRuleList
                .Where(p => parameterDictionary.ContainsKey(p) && parameterDictionary[p].ContainsKey("序号"))
                .Select(paramName => new
                {
                    ParamName = paramName,
                    Order = parameterDictionary[paramName]["序号"]
                })
                .OrderByDescending(x => x.Order)
                .Select(x => x.ParamName)
                .ToList();
        }

        private void InitToolTipTimer()
        {
            // 初始化 Timer，控制 ToolTip 显示时间
            tooltipTimer = new Timer();
            tooltipTimer.Interval = 2000;  // 设置为2秒
            tooltipTimer.Tick += TooltipTimer_Tick;
        }

        // Timer 到期时清除所有单元格的 ToolTip
        private void TooltipTimer_Tick(object sender, EventArgs e)
        {
            tooltipTimer.Stop();  // 停止 Timer
            ClearAllCellToolTips();  // 清除所有 ToolTip
        }

        // 清除所有单元格的 ToolTip
        private void ClearAllCellToolTips()
        {
            foreach (DataGridViewRow row in UIGrid.Rows)
            {
                foreach (DataGridViewCell cell in row.Cells)
                {
                    cell.ToolTipText = string.Empty;
                }
            }
        }

        private void ShowToolTip(int rowIndex, int colIndex, string message)
        {
            ToolTip toolTip = new ToolTip();
            toolTip.IsBalloon = true;
            // 获取单元格的屏幕位置
            Rectangle cellDisplayRectangle = UIGrid.GetCellDisplayRectangle(-1, -1, true);
            Point cellPosition = UIGrid.PointToScreen(new Point(cellDisplayRectangle.X, cellDisplayRectangle.Y));
            // 设置ToolTip的位置在单元格的上方
            toolTip.Show(message, this, 0, cellPosition.Y, 1000); // 3秒后消失
        }

        public static Dictionary<string, Dictionary<string, string>> ParseRules(string rulesText)
        {
            var result = new Dictionary<string, Dictionary<string, string>>();

            if (string.IsNullOrWhiteSpace(rulesText))
            {
                return result; // 返回空字典
            }

            // 定义支持的运算符
            var operators = new[] { ">=", "<=", ">", "<", "=" };

            // 将规则文本按';'进行分割
            var rules = rulesText.Split(new[] { ';','；' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var rule in rules)
            {
                foreach (var op in operators)
                {
                    var parts = rule.Split(new[] { op }, 2, StringSplitOptions.RemoveEmptyEntries);

                    if (parts.Length == 2)
                    {
                        var key = parts[0].Trim();
                        var value = parts[1].Trim();

                        if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
                        {
                            result[key] = new Dictionary<string, string>
                        {
                            { "运算符", op },
                            { "值", value }
                        };
                        }
                        break;
                    }
                }
            }

            return result;
        }

        public void AnalyzeRules()
        {
            try
            {
                var parameterDictionary = UIConfigModel.Instance.GetGridDataDict();
                if (parameterDictionary == null)
                {
                    Logger.Instance.Log("Warning: parameterDictionary is null in AnalyzeRules");
                    return;
                }

                foreach (var parameter in parameterDictionary)
                {
                    string parameterName = parameter.Key;
                    if (parameter.Value.TryGetValue("显示规则", out var showRuleObj))
                    {
                        string sShowRule = showRuleObj?.ToString() ?? string.Empty;
                        var dRules = ParseRules(sShowRule);
                        parsedRules[parameterName] = dRules;
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Instance.Log($"Error in AnalyzeRules: {ex.Message}");
                Logger.Instance.Log($"Stack Trace: {ex.StackTrace}");
            }
        }

        public void GenerateMapping()
        {
            var dictionaryB = new Dictionary<string, List<string>>();
            var delimiters = new[] { "+", "-", "*", "/", "÷", "×" }; // 定义分割符

            foreach (var outerKvp in parsedRules)
            {
                var outerKey = outerKvp.Key;

                foreach (var innerKey in outerKvp.Value.Keys)
                {
                    // 去掉中英文括号
                    var cleanedKey = Regex.Replace(innerKey, @"[()（）]", string.Empty);

                    // 按照分割符拆分键
                    var splitKeys = cleanedKey.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var key in splitKeys)
                    {
                        var trimmedKey = key.Trim();

                        if (!dictionaryB.ContainsKey(trimmedKey))
                        {
                            dictionaryB[trimmedKey] = new List<string>();
                        }

                        if (!dictionaryB[trimmedKey].Contains(outerKey)) 
                        {
                            dictionaryB[trimmedKey].Add(outerKey);
                        }
                        
                    }
                }
            }

            ParaRuleMap = dictionaryB;
        }

        public bool IsRuleMatch(string sSubRuleKey)
        {
            var delimiters = new[] { "+", "-", "*", "/", "÷", "×" }; // 定义分割符
            var keyColValues = new HashSet<string>();

            // 遍历 DataGridView 的所有行
            foreach (DataGridViewRow row in UIGrid.Rows)
            {
                // 将每一行 "KeyCol" 列中的值添加到集合中
                var keyValue = row.Cells["KeyCol"].Value?.ToString();
                if (!string.IsNullOrEmpty(keyValue))
                {
                    keyColValues.Add(keyValue);
                }
            }

            if (parsedRules.ContainsKey(sSubRuleKey))
            {
                var dRules = parsedRules[sSubRuleKey];
                foreach(var ruleKvp in dRules)
                {
                    var cleanedKey = Regex.Replace(ruleKvp.Key, @"[()（）]", string.Empty);
                    var splitKeys = cleanedKey.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
                    foreach (var key in splitKeys)
                    {
                        if (!keyColValues.Contains(key))
                        {
                            return false;
                        }
                    }
                    var iResult = CalculateStringExpression(cleanedKey);
                    var dValue = ruleKvp.Value;
                    string sJudge = iResult.ToString() + dValue["运算符"] + dValue["值"];
                    if (!EvaluateComparisonExpression(sJudge))
                    {
                        return false;
                    }

                }
                return true;
            }
            else
            {
                return false;
            }
        }

        public object GetValueColByKeyCol(string key)
        {
            foreach (DataGridViewRow row in UIGrid.Rows)
            {
                if (row.Cells["KeyCol"].Value?.ToString() == key)
                {
                    var value = row.Cells["ValueCol"].Value?.ToString();

                    if (decimal.TryParse(value, out decimal numericValue))
                    {
                        return numericValue;
                    }

                    return value;
                }
            }

            return null; // 如果未找到匹配的行，返回 null
        }

        public object CalculateStringExpression(string expression)
        {
            string[] operators = { "+", "-", "*", "/", "÷", "×" };

            // 递归处理表达式
            object EvaluateExpression(string expr)
            {
                foreach (var op in operators)
                {
                    // 使用最后出现的运算符进行分割，优先级从低到高
                    int operatorIndex = expr.LastIndexOf(op);
                    if (operatorIndex > 0)
                    {
                        string leftPart = expr.Substring(0, operatorIndex).Trim();
                        string rightPart = expr.Substring(operatorIndex + 1).Trim();

                        var leftValue = EvaluateExpression(leftPart);
                        var rightValue = EvaluateExpression(rightPart);

                        // 检查值是否可以转换为decimal
                        if (decimal.TryParse(leftValue?.ToString(), out decimal leftDecimal) &&
                            decimal.TryParse(rightValue?.ToString(), out decimal rightDecimal))
                        {
                            switch (op)
                            {
                                case "+":
                                    return leftDecimal + rightDecimal;
                                case "-":
                                    return leftDecimal - rightDecimal;
                                case "*":
                                case "×":
                                    return leftDecimal * rightDecimal;
                                case "/":
                                case "÷":
                                    if (rightDecimal == 0)
                                    {
                                        Logger.Instance.Log("错误：除数不能为零");
                                        return null;
                                    }
                                    return leftDecimal / rightDecimal;
                            }
                        }
                        else
                        {
                            Logger.Instance.Log("错误：无法获取有效的数值进行运算");
                            return null;
                        }
                    }
                }

                // 当没有运算符时，直接获取数值
                var singleValue = GetValueColByKeyCol(expr.Trim());
                if (decimal.TryParse(singleValue?.ToString(), out decimal result))
                {
                    return result;
                }
                else
                {
                    Logger.Instance.Log($"错误：无法获取有效的数值 {singleValue}");
                    return singleValue;
                }
            }

            return EvaluateExpression(expression);
        }

        public bool EvaluateComparisonExpression(string expression)
        {
            try
            {
                // 检查表达式是否包含等号，但不包含其他比较运算符（如 >, <, >=, <=）
                if (expression.Contains("=") && !expression.Contains(">") && !expression.Contains("<"))
                {
                    // 以等号分割字符串并去除空格
                    var parts = expression.Split('=').Select(p => p.Trim()).ToArray();

                    // 如果左右部分相等，返回true
                    if (parts.Length == 2 && parts[0] == parts[1])
                    {
                        return true;
                    }
                    else if (parts.Length == 2)
                    {
                        return false;
                    }
                    else
                    {
                        throw new ArgumentException("Invalid expression.");
                    }
                }

                // 如果不是简单字符串比较，使用NCalc进行数值计算
                var expr = new Expression(expression);
                var result = expr.Evaluate();

                // 返回计算结果
                if (result is bool boolResult)
                {
                    return boolResult;
                }

                throw new ArgumentException("The expression did not evaluate to a boolean value.");
            }
            catch (Exception ex)
            {
                // 捕获任何错误并返回false
                Logger.Instance.Log($"Error evaluating expression: {ex.Message}");
                return false;
            }
        }

        public Dictionary<string, object> GetDataFromUIGrid()
        {
            // 创建一个新的字典来存储数据
            Dictionary<string, object> dataDictionary = new Dictionary<string, object>();

            // 遍历UIGrid中的每一行
            foreach (DataGridViewRow row in UIGrid.Rows)
            {
                // 获取"KeyCol"和"ValueCol"对应的单元格的值
                var key = row.Cells["KeyCol"].Value?.ToString();
                string valueCell = row.Cells["ValueCol"].Value?.ToString();
                string Unit = row.Cells["UnitCol"].Value?.ToString();
                string sDealCellValue = "";

                if (double.TryParse(valueCell, out double newDimensionValue))
                {
                    double DealCellValue;
                    if (Unit == "mm")
                    {
                        DealCellValue = newDimensionValue / 1000.0;
                    }
                    else
                    {
                        DealCellValue = newDimensionValue;
                    }   
                    sDealCellValue = DealCellValue.ToString();
                }
                else
                {
                    sDealCellValue = valueCell.ToString();
                }

                if (!string.IsNullOrEmpty(key))
                {
                    // 将KeyCol的值作为字典的键，ValueCol的值作为字典的值
                    dataDictionary[key] = sDealCellValue;
                }
            }

            return dataDictionary;
        }

        public bool CheckGridEmpty()
        {
            if (UIGrid.Rows.Count > 0 && UIGrid.Rows[0].IsNewRow == false)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public bool CanPackAndGo()
        {
            return PackAndGoCheck.Checked;
        }
        #region AI驱动

        private void AddUserInput(string sInput)
        {
            richTextBox2.SelectionStart = richTextBox2.TextLength;
            richTextBox2.SelectionAlignment = HorizontalAlignment.Right;
            richTextBox2.SelectionColor = Color.Red;
            richTextBox2.SelectionFont = new Font("Arial", 14, FontStyle.Bold);
            richTextBox2.AppendText("User1:\r\n");
            richTextBox2.ScrollToCaret();

            richTextBox2.SelectionColor = Color.Black;
            richTextBox2.SelectionAlignment = HorizontalAlignment.Left;
            richTextBox2.SelectionFont = new Font("Arial", 10, FontStyle.Bold);
            richTextBox2.AppendText($"{sInput}\r\n");
            richTextBox2.ScrollToCaret();
        }

        public void AddModelInput(string sInput)
        {
            if (richTextBox2.InvokeRequired)
            {
                richTextBox2.Invoke(new Action(() => AppendInputToRichTextBox1()));
            }
            else
            {
                AppendInputToRichTextBox1();
            }
            AddModelContent(sInput);
        }

        public async void AddModelContent(string sInput)
        {
            await StreamOutputToRichTextBox(sInput);
        }

        private async Task StreamOutputToRichTextBox(string sInput)
        {
            Random random = new Random();
            int index = 0;

            while (index < sInput.Length)
            {
                // 每次输出的随机字符数，范围为2到5
                int n = random.Next(2, 6);

                // 如果剩余字符不足，则输出剩余全部字符
                int length = Math.Min(n, sInput.Length - index);

                // 提取当前批次的字符
                string currentText = sInput.Substring(index, length);
                index += length;

                // 更新UI控件（使用异步上下文）
                if (richTextBox2.InvokeRequired)
                {
                    richTextBox2.Invoke(new Action(() => AppendInputToRichTextBox(currentText)));
                }
                else
                {
                    AppendInputToRichTextBox(currentText);
                }

                // 延时模拟流式输出，随机间隔50-100毫秒
                await Task.Delay(random.Next(50, 101));
            }

            // 流式输出完成后的额外操作，如换行
            AppendInputToRichTextBox("\r\n");
            ResetRichTextBoxState();
        }

        public void ResetRichTextBoxState()
        {
            // 如果在非UI线程上调用，则使用Invoke
            if (richTextBox2.InvokeRequired)
            {
                richTextBox2.Invoke(new Action(() => ResetRichTextBoxState()));
                return;
            }

            richTextBox2.SelectionColor = Color.Red;
            richTextBox2.SelectionFont = new Font("Arial", 14, FontStyle.Bold);
        }

        public void AppendInputToRichTextBox1()
        {
            richTextBox2.SelectionColor = Color.Blue;
            richTextBox2.SelectionFont = new Font("Arial", 14, FontStyle.Bold);
            richTextBox2.AppendText("宇喜AI助理:\r\n");
        }

        public void AppendInputToRichTextBox(string sInput)
        {
            // 如果在非UI线程上调用，则使用Invoke
            if (richTextBox2.InvokeRequired)
            {
                richTextBox2.Invoke(new Action(() => AppendInputToRichTextBox(sInput)));
                return;
            }

            // 设置颜色和样式
            richTextBox2.SelectionColor = Color.Black;
            richTextBox2.SelectionFont = new Font("Arial", 10, FontStyle.Bold);

            // 添加文本
            richTextBox2.AppendText(sInput);

            // 滚动到最新文本
            //richTextBox2.ScrollToCaret();
            EnsureScrollToBottom(richTextBox2);
        }

        #region AI搜索
        private void AddUserInput2(string sInput)
        {
            richTextBox1.SelectionStart = richTextBox1.TextLength;
            richTextBox1.SelectionAlignment = HorizontalAlignment.Right;
            richTextBox1.SelectionColor = Color.Red;
            richTextBox1.SelectionFont = new Font("Arial", 14, FontStyle.Bold);
            richTextBox1.AppendText("User1:\r\n");
            richTextBox1.ScrollToCaret();

            richTextBox1.SelectionColor = Color.Black;
            richTextBox1.SelectionAlignment = HorizontalAlignment.Left;
            richTextBox1.SelectionFont = new Font("Arial", 10, FontStyle.Bold);
            richTextBox1.AppendText($"{sInput}\r\n");
            richTextBox1.ScrollToCaret();
        }

        public void AddModelInput2(string sInput)
        {
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.Invoke(new Action(() => AppendInputToRichTextBox2()));
            }
            else
            {
                AppendInputToRichTextBox2();
            }
            AddModelContent2(sInput);
        }

        public async void AddModelContent2(string sInput)
        {
            await StreamOutputToRichTextBox2(sInput);
        }

        private async Task StreamOutputToRichTextBox2(string sInput)
        {
            Random random = new Random();
            int index = 0;

            while (index < sInput.Length)
            {
                // 每次输出的随机字符数，范围为2到5
                int n = random.Next(2, 6);

                // 如果剩余字符不足，则输出剩余全部字符
                int length = Math.Min(n, sInput.Length - index);

                // 提取当前批次的字符
                string currentText = sInput.Substring(index, length);
                index += length;

                // 更新UI控件（使用异步上下文）
                if (richTextBox1.InvokeRequired)
                {
                    richTextBox1.Invoke(new Action(() => AppendInputToRichTextBox2(currentText)));
                }
                else
                {
                    AppendInputToRichTextBox2(currentText);
                }

                // 延时模拟流式输出，随机间隔50-100毫秒
                await Task.Delay(random.Next(50, 101));
            }

            // 流式输出完成后的额外操作，如换行
            AppendInputToRichTextBox2("\r\n");
            ResetRichTextBoxState2();
            OnSearchOutPutFinish.Invoke();
        }

        public void ResetRichTextBoxState2()
        {
            // 如果在非UI线程上调用，则使用Invoke
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.Invoke(new Action(() => ResetRichTextBoxState2()));
                return;
            }

            richTextBox1.SelectionColor = Color.Red;
            richTextBox1.SelectionFont = new Font("Arial", 14, FontStyle.Bold);
        }


        public void AppendInputToRichTextBox2()
        {
            richTextBox1.SelectionColor = Color.Blue;
            richTextBox1.SelectionFont = new Font("Arial", 14, FontStyle.Bold);
            richTextBox1.AppendText("宇喜AI助理:\r\n");
        }

        public void AppendInputToRichTextBox2(string sInput)
        {
            // 如果在非UI线程上调用，则使用Invoke
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.Invoke(new Action(() => AppendInputToRichTextBox2(sInput)));
                return;
            }

            // 设置颜色和样式
            richTextBox1.SelectionColor = Color.Black;
            richTextBox1.SelectionFont = new Font("Arial", 10, FontStyle.Bold);

            // 添加文本
            richTextBox1.AppendText(sInput);

            // 滚动到最新文本
            //richTextBox1.ScrollToCaret();
            EnsureScrollToBottom(richTextBox1);
        }

        public static bool IsScrolledToBottom(RichTextBox richTextBox)
        {
            int lastCharIndex = richTextBox.TextLength;
            Point lastCharPos = richTextBox.GetPositionFromCharIndex(lastCharIndex);

            return lastCharPos.Y <= richTextBox.ClientRectangle.Height - richTextBox.Font.Height;
        }

        public static void EnsureScrollToBottom(RichTextBox rtb)
        {
            if (!IsScrolledToBottom(rtb))
            {
                rtb.SelectionStart = rtb.TextLength;
                rtb.ScrollToCaret();
            }
        }

        #endregion

        public void TestSendMsg()
        {
            AddUserInput(textBox2.Text);
            CallModel?.Invoke(textBox2.Text);
            textBox2.Text = "";
            textBox2.Enabled = false;
        }

        public void TestSendMsg2()
        {
            AddUserInput2(textBox1.Text);
            CallModel2?.Invoke(textBox1.Text);
            textBox1.Text = "";
            textBox1.Enabled = false;
        }

        public void ReActiveTextBox()
        {
            // 如果在非UI线程上调用，则使用Invoke
            if (textBox2.InvokeRequired)
            {
                textBox2.Invoke(new Action(() => ReActiveTextBox()));
                return;
            }

            textBox2.Enabled = true;

            if (textBox1.InvokeRequired)
            {
                textBox1.Invoke(new Action(() => ReActiveTextBox()));
                return;
            }

            textBox1.Enabled = true;
        }

        public void InsertNewLink(Dictionary<string, string> Name2Path)
        {
            foreach(var Kvp in Name2Path)
            {
                if (richTextBox1.InvokeRequired)
                {
                    richTextBox1.Invoke(new Action(() => InsertLinkLine(
                    ($"<在PDM中打开{Kvp.Key}>", new LinkInfo("Find", $@"{Kvp.Value}")),
                    ("<在solidworks中打开>", new LinkInfo("Open", $@"{Kvp.Value}"))
                )));
                }
                else
                {
                    InsertLinkLine(
                    ($"<在PDM中打开{Kvp.Key}>", new LinkInfo("Find", $@"{Kvp.Value}")),
                    ("<在solidworks中打开>", new LinkInfo("Open", $@"{Kvp.Value}"))
                );
                }
            }
        }

        private void InsertLinkLine(params (string displayText, LinkInfo info)[] links)
        {
            var defaultFont = richTextBox1.Font; // 记录默认字体
            float linkFontSize = 9f;            // 设置你希望的链接字号

            foreach (var (text, info) in links)
            {
                int start = richTextBox1.TextLength;

                // 设置链接字体和样式
                richTextBox1.SelectionFont = new Font(defaultFont.FontFamily, linkFontSize, FontStyle.Bold);
                richTextBox1.SelectionColor = Color.Blue;

                // 插入链接文本
                richTextBox1.AppendText(text + "\t"); // 用制表符分隔

                //// 设置为"伪链接样式"
                //richTextBox1.Select(start, text.Length);
                //richTextBox1.SelectionColor = Color.Blue;
                //richTextBox1.SelectionFont = new Font(richTextBox1.Font, FontStyle.Bold);


                // 添加映射
                // 记录点击区域
                linkRanges.Add(new LinkRange
                {
                    StartIndex = start,
                    Length = text.Length,
                    Info = info
                });
            }

            //richTextBox1.SelectionFont = defaultFont;
            //richTextBox1.SelectionColor = Color.Black;
            richTextBox1.AppendText(System.Environment.NewLine);
        }

        public void AddQuot()
        {
            if (richTextBox1.InvokeRequired)
            {
                richTextBox1.Invoke(new Action(() => AddQuot()));
                return;
            }
            richTextBox1.AppendText(System.Environment.NewLine);
        }

        #endregion

        private void OnOpenWindowBtnClick()
        {
            OpenWindowBtnClick?.Invoke();
        }
        
        private void OnSaveFileBtnClick()
        {
            SaveFileBtnClick?.Invoke();
        }
        private void ShowMainForm1()
        {
            ShowMainForm?.Invoke();
        }

        private void oEditNowConfigBtn_Click(object sender, EventArgs e)
        {
            
            EditNowConfigClick?.Invoke();
            ToggleControl(tableLayoutPanel3, new dlgSubPage.dlgRename(iSwApp));
        }

        private void oEditSelectConfigBtn_Click(object sender, EventArgs e)
        {
            EditSelectConfigClick?.Invoke();
            ToggleControl(tableLayoutPanel3, new dlgSubPage.dlgRename(iSwApp));
            
        }

        private void oOpenConfigFileBtn_Click(object sender, EventArgs e)
        {
            OpenConfigFileClick?.Invoke();
            //try
            //{
            //    ToggleControl(oOpenConfigFileBtn, new dlgSubPage.dlgRename(iSwApp));
            //}
            //catch (Exception ex)
            //{
            //    Logger.Instance.Log($"Stack Trace: {ex.StackTrace}");
            //    MessageBox.Show($"Error in TaskPaneHost_OpenConfigFileClick: {ex.Message}");
            //}

        }

        private void oTestBtn_Click(object sender, EventArgs e)
        {
            //TestBtnClick?.Invoke();
            Logger.Instance.ShowDecodeDialog(this);
        }

        private void oDriveBtn_Click(object sender, EventArgs e)
        {
            DriveBtnClick?.Invoke();
        }

        private void ChangeBtn_Click(object sender, EventArgs e)
        {
            ToggleControl(tableLayoutPanel3, new dlgSubPage.dlgRename(iSwApp));
            ChangeBtnClick?.Invoke();
            SetEditPartShow(false);
        }

        // 点击按钮单元格时触发的事件
        private void DataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否点击的是"示例图"列中的按钮
            if (UIGrid.Columns[e.ColumnIndex].Name == "PicCol" && e.RowIndex >= 0)
            {
                // 获取当前行中"参数"列和"值"列的数据
                string parameter = UIGrid.Rows[e.RowIndex].Cells["PicCol"].Tag?.ToString();

                // 调用回调函数并传入参数
                OnExampleButtonClick(parameter);
            }
        }

        // 回调函数，处理按钮点击事件
        private void OnExampleButtonClick(string parameter)
        {
            try
            {
                dlgImageViewer viewer = new dlgImageViewer(parameter);
                viewer.ShowDialog(); // 模态显示图片预览界面
            }
            catch (Exception ex)
            {
                Logger.Instance.Log($"Error in OnExampleButtonClick: {ex.Message}");
                Logger.Instance.Log($"Stack Trace: {ex.StackTrace}");
            }

        }

        private void UIGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {
            TestSendMsg();
        }

        private void textBox2_TextChanged(object sender, EventArgs e)
        {

        }

        private void tabPage2_Resize(object sender, EventArgs e)
        {
            Logger.Instance.Log($"tabPage2_Resize = width:{tabPage2.Width}, height:{tabPage2.Height}");
            int spacing = 3; // 控件间隔

            // 固定高度
            int textBoxHeight = panel2.Height;

            // 计算RichTextBox的高度
            int richTextBoxHeight = tabPage1.Height - textBoxHeight - (spacing * 3);

            // 设置控件位置和高度
            richTextBox2.Height = Math.Max(0, richTextBoxHeight);
            panel2.Top = richTextBox2.Bottom + spacing;
        }


        private void CloseBtn_Click(object sender, EventArgs e)
        {
            CloseBtnClick.Invoke();
        }

        private void panel7_Paint(object sender, PaintEventArgs e)
        {

        }

        private void openLogBtn_Click(object sender, EventArgs e)
        {
            string dllPath = Logger.Instance.GetDLLPath();
            Process.Start("explorer.exe", Path.Combine(dllPath, "logfile"));
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void tabControl1_Resize(object sender, EventArgs e)
        {

        }

        private void tabPage3_Resize(object sender, EventArgs e)
        {
            Logger.Instance.Log($"tabPage3_Resize = width:{tabPage3.Width}, height:{tabPage3.Height}");
            int spacing = 3; // 控件间隔

            // 固定高度
            int textBoxHeight = panel6.Height;

            // 计算RichTextBox的高度
            int richTextBoxHeight = tabPage3.Height - textBoxHeight - (spacing * 3);

            // 设置控件位置和高度
            richTextBox1.Height = Math.Max(0, richTextBoxHeight);
            panel7.Top = richTextBox1.Bottom + spacing;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            TestSendMsg2();
        }

        private void richTextBox1_LinkClicked(object sender, LinkClickedEventArgs e)
        {
            if (linkMap.TryGetValue(e.LinkText, out LinkInfo info))
            {
                Logger.Instance.Log($"你点击了：{info.Path}");
                if(info.Action == "Find")
                {
                    // 打开文件夹
                    if (Directory.Exists(info.Path))
                    {
                        Process.Start("explorer.exe", $"/select,\"{info.Path}\"");
                    }
                    else
                    {
                        MessageBox.Show($"路径不存在：{info.Path}");
                    }
                }
                else if (info.Action == "Open")
                {
                    OpenSearchFile.Invoke(info.Path);
                }
                else
                {
                    MessageBox.Show($"路径不存在：{info.Path}");
                }
            }
        }

        private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
        {
            int clickedIndex = richTextBox1.GetCharIndexFromPosition(e.Location);

            foreach (var link in linkRanges)
            {
                if (clickedIndex >= link.StartIndex && clickedIndex < link.StartIndex + link.Length)
                {
                    Logger.Instance.Log($"你点击了：{link.Info.Path}");
                    if (link.Info.Action == "Find")
                    {
                        // 选中文件
                        if (File.Exists(link.Info.Path))
                        {
                            Process.Start("explorer.exe", $"/select,\"{link.Info.Path}\"");
                        }
                        else
                        {
                            MessageBox.Show($"路径不存在：{link.Info.Path}");
                        }
                    }
                    else if (link.Info.Action == "Open")
                    {
                        OpenSearchFile.Invoke(link.Info.Path);
                    }
                    else
                    {
                        MessageBox.Show($"路径不存在：{link.Info.Path}");
                    }

                    break;
                }
            }
        }
    }
}
